package lg.minecraft.plugin.pokedex;

import com.cobblemon.mod.common.api.pokemon.PokemonSpecies;
import com.cobblemon.mod.common.pokemon.Species;
import lg.minecraft.plugin.library.LGPlugin;
import lg.minecraft.plugin.pokedex.command.*;
import lg.minecraft.plugin.pokedex.config.*;
import lg.minecraft.plugin.pokedex.listener.PlayerEvent;
import lg.minecraft.plugin.pokedex.manager.PokedexPlayerManger;
import lg.minecraft.plugin.pokedex.storage.DataStorage;
import lg.minecraft.plugin.pokedex.storage.MYSQLStorage;
import lg.minecraft.plugin.pokedex.task.PlayerDataTask;
import lombok.Getter;
import org.bukkit.Bukkit;

import java.util.Comparator;
import java.util.List;

public final class LGPokedex extends LGPlugin {

    @Getter private static List<Species> speciesList;

    @Getter private static LGPokedex instance;

    @Getter private static PokedexPlayerManger pokedexPlayerManger;

    private static PlayerDataTask playerDataTask;

    @Override
    public void onEnable() {
        instance = this;
        initSpeciesList();
        MainCommand mainCommand = new MainCommand();
        mainCommand.registerSubCommand(new SubOpenCommand());
        mainCommand.registerSubCommand(new SubGrantCommand());
        mainCommand.registerSubCommand(new SubRevokeCommand());
        mainCommand.registerSubCommand(new SubReloadCommand());
        pokedexPlayerManger = new PokedexPlayerManger();
        Bukkit.getPluginManager().registerEvents(new PlayerEvent(), this);
        playerDataTask = new PlayerDataTask();
        playerDataTask.start();
    }

    @Override
    public void onDisable() {
        if (playerDataTask != null) playerDataTask.stop();
        DataStorage dataStorage = pokedexPlayerManger.getDataStorage();
        if (dataStorage instanceof MYSQLStorage) {
            ((MYSQLStorage) dataStorage).close();
        }
    }

    public static void reload() {
        MainConfig.INSTANCE.load();
        MessageConfig.INSTANCE.load();
        RewardConfig.INSTANCE.load();
        GuiItemConfig.INSTANCE.load();
        initSpeciesList();
    }

    public static void initSpeciesList() {
        speciesList = PokemonSpecies.getSpecies().stream()
                .sorted(Comparator.comparingInt(Species::getNationalPokedexNumber))
                .toList();
    }

}
